<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>照片墙</title>
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.css">
  <link rel="stylesheet" href="https://fastly.jsdelivr.net/npm/font-awesome/css/font-awesome.min.css"/>
  <link rel="stylesheet" href="../static/css/animate.css" th:href="@{/css/animate.css}">
  <link rel="stylesheet" href="../static/css/me.css" th:href="@{/css/me.css}">
  <link rel="stylesheet" href="../static/lib/picture/css/jkresponsivegallery.css"
        th:href="@{/lib/picture/css/jkresponsivegallery.css}">
  <style>
      .edit-delete-buttons {
          position: relative;
          float: right;
          padding-right: 30px;
      }

      /* 根据需要调整按钮的垂直对齐方式 */
      .edit-delete-buttons .ui.button {
          color: #f17000;
          opacity: 0.9;
          border-radius: 0.6em;
      }
  </style>
</head>
<body class="archiveBody">

<!--导航-->
<nav class="gird-header">
  <div class="ui container" style="width: 95%!important;"> <!-- 加一个容器 -->
    <div class="ui inverted secondary stackable menu"> <!-- 菜单 stackable:可堆叠的,表示屏幕小时自动堆叠-->
      <a th:href="@{/user_index}"><h2 class="ui white header item">GuideSystem</h2></a> <!-- 蓝绿色标题 -->
      <a href="#" th:href="@{/user_index}" class="m-item m-mobile-hide item"><i class="home icon"></i>首页</a>
      <!-- icon表示图标 -->
      <a href="#" th:href="@{/user_forum}" class="m-item m-mobile-hide item"><i class="comments icon"></i>论坛</a>
      <a href="#" th:href="@{/user_types/-1}" class="m-item m-mobile-hide item"><i class="idea icon"></i>分类</a>
      <a href="#" th:href="@{/about}" class="m-item m-mobile-hide item"><i class="info icon"></i>我的</a>
      <div class="m-top-right m-mobile-hide item m-item" style="margin: auto; margin-top: -5px;"> <!-- 靠右 -->
        <form name="search" method="get" action="#" th:action="@{/user_search}" target="_blank">
          <div class="ui icon input">
            <input type="text" name="query" placeholder="Search..." th:value="${query}">
            <i onclick="document.forms['search'].submit()" class="search link icon"></i>
          </div>
        </form>
        <div class="ui dropdown item">
          <div class="container">
            <img src="../static/images/店铺1.jpg" th:src="@{${session.user?.avatar}}" alt="" class="ui avatar image"
                 style="object-fit: cover;
                       outline: 0px;
                       background-size: 100% 100%;">
          </div>
          <i class="dropdown icon"></i>
          <div class="menu">
            <a href="#" th:href="@{/about}" target="_blank" class="item">我的</a>
            <a href="#" th:href="@{/edit/password}" class="item">修改密码</a>
            <a href="#" th:href="@{/login/exit}" id="logout-link" class="item">退出</a>
            <a href="#" onclick="deleteAccount()" class="item">注销</a> <!--得更新-->
          </div>
        </div>
      </div>
    </div>
  </div>
  <a href="#" class="ui menu toggle black button icon m-top-right m-mobile-show">
    <i class="sidebar icon"></i>
  </a>
</nav>

<!--顶部图片-->
<div class="m-bg-type_outer" style="width: 100%; margin-top: 4.4em !important;">
  <div class="m-bg-class_coverPicture">
    <div class="ui container" style="margin: auto; padding-top: 10px">
      <div class="m-font-size-title m-right-bottom" align="center" style="font-family:'STXingkai'">照片墙</div>
      <div class="m-font-size-text-init-title m-margin-top" align="center">愿你走出半生，归来仍是少年</div>
    </div>
  </div>
</div>

<!--照片墙-->
<div class="ui m-container-alter transparent-segment segment m-margin-tb-large">
  <div class="m-margin-buttom-large" th:if="${session.user?.id == user?.id}"> <!--就不管啥安全不安全的了-->
    <div class="ui form" style="float: right !important;">
      <div class="inline field" style="padding-right: 18px;">
        <div class="ui toggle checkbox">
          <input type="checkbox" tabindex="0" class="hidden">
          <label style="font-weight: bold">操作</label>
        </div>
        <button class="circle-button" style="border-radius: .9rem !important; color: #f17000" id="addPicture">
          添加
        </button>
      </div>
    </div>
  </div>
  <div id="picture-main" style="margin-left: 12px; margin-right: -10px">
    <article class="thumb" th:each="picture, iterStat: ${pagePicture.list}">
      <div>
        <div class="rthumbnail">
          <a href="../static/images/archiveImg_2.jpg" th:href="@{${picture?.pictureAddress}}">
            <img class="picture-zmki_px" src="../static/images/archiveImg_2.jpg" style="border-radius: .6rem !important"
                 th:src="@{${picture?.pictureAddress}}">
          </a>
          <div class="m-picture-text" th:text="${picture?.pictureName}">起风了</div>
          <div class="rcaption">
            <div style="font-size: x-large;" th:text="${picture?.pictureName}">起风了</div>
            <div style="font-size: 16px" class="m-margin-top" th:text="${picture?.pictureTime}">2024-03-21 &nbsp;南昌
            </div>
            <p style="font-size: 16px" th:text="${picture?.pictureDescription}">
              我曾难自拔于世界之大，也沉迷于其中梦话</p>
          </div>
        </div>
      </div>
      <div class="edit-delete-buttons" style="position: relative; display: none;">
        <div class="ui button" th:onclick="editPicture([[${picture.id}]])">编辑</div>
        <div class="ui button danger" th:onclick="deletePicture([[${picture.id}]])">删除</div>
      </div>
    </article>
    <!--/*-->
    <article class="thumb">
      <div>
        <div class="rthumbnail">
          <a href="../static/images/archiveImg_1.jpg" th:href="@{${picture.pictureaddress}}">
            <img class="picture-zmki_px" src="../static/images/archiveImg_1.jpg" style="border-radius: .6rem !important"
                 th:src="@{${picture.pictureaddress}}">
          </a>
          <div class="m-picture-text" th:text="${picture.picturename}">起风了</div>
          <div class="rcaption">
            <div style="font-size: large;" th:text="${picture.picturename}">起风了</div>
            <div style="font-size: 16px" class="m-margin-top" th:text="${picture.picturetime}">2024-03-21 &nbsp;南昌
            </div>
            <p style="font-size: 16px" th:text="${picture.picturedescription}">
              我曾难自拔于世界之大，也沉迷于其中梦话</p>
          </div>
        </div>
      </div>
      <div class="edit-delete-buttons" style="position: relative; display: none;">
        <div class="ui button" onclick="editPicture()">编辑</div>
        <div class="ui button danger" onclick="deletePicture()">删除</div>
      </div>
    </article>
    <!--*/-->
  </div>

  <!--分页footer-->
  <div class="ui attached segment" style="background-color: transparent !important; border-style: none; height: 45px;"
       th:if="${pagePicture.total}>1">
    <div class="ui  aligned two column grid"> <!-- middle aligned:垂直方向居中 -->
      <!--左侧-->
      <th:block
          th:with="targetUrl = ${session.user?.id != user?.id ? '/picture/list/' + user?.id : '/picture/me/list'}">
        <div class="left aligned column" style="padding-left: 2em !important;">
          <a href="#" th:href="@{__${targetUrl}__(pageNum=${pagePicture.hasPreviousPage}?${pagePicture.prePage}:1)}"
             th:unless="${pagePicture.isFirstPage}" class="ui mini blue basic button">上一页</a> <!-- 小按钮 -->
        </div>
      </th:block>
      <!--右侧-->
      <th:block
          th:with="targetUrl = ${session.user?.id != user?.id ? '/picture/list/' + user?.id : '/picture/me/list'}">
        <div class="right aligned column" style="padding-right: 2.2em !important;">
          <a href="#"
             th:href="@{__${targetUrl}__(pageNum=${pagePicture.hasNextPage}?${pagePicture.nextPage}:${pagePicture.pages})}"
             th:unless="${pagePicture.isLastPage}" class="ui mini blue basic button">下一页</a> <!-- 小按钮 -->
        </div>
      </th:block>
    </div>
  </div>

  <!--添加图片模态框-->
  <div class="ui addPicture modal">
    <i class="close icon"></i>
    <h3 style="padding-left: 1em !important; font-size: x-large !important; padding-bottom: 0.1em !important;">
      添加图片</h3>
    <form class="ui form segment" method="post" action="#" th:action="@{/picture/me/save}">
      <input type="hidden" name="userId" th:value="${session.user?.id}">
      <div class="two fields">
        <div class="field" style="width: 30% !important;">
          <label>名称</label>
          <input placeholder="请输入名称..." name="pictureName" type="text">
        </div>
        <div class="field" style="width: 70% !important;">
          <label>链接</label>
          <input placeholder="请输入图片链接..." name="pictureAddress" type="text">
        </div>
      </div>
      <div class="field">
        <label>描述</label>
        <textarea placeholder="请输入描述..." name="pictureDescription" type="text" style="height: 80px"></textarea>
      </div>
      <div class="actions">
        <div class="ui primary submit button">提交</div>
        <div class="ui clear button">重置</div>
      </div>
    </form>
  </div>

  <!--编辑图片模态框-->
  <div class="ui editPicture modal">
    <i class="close icon"></i>
    <h3 style="padding-left: 1em !important; font-size: x-large !important; padding-bottom: 0.1em !important;">
      编辑图片</h3>
    <form class="ui form segment" method="post" action="#" th:action="@{/picture/me/edit}">
      <input type="hidden" name="userId">
      <input type="hidden" name="id">
      <div class="two fields">
        <div class="field" style="width: 30% !important;">
          <label>名称</label>
          <input placeholder="请输入名称..." name="pictureName" type="text">
        </div>
        <div class="field" style="width: 70% !important;">
          <label>链接</label>
          <input placeholder="请输入图片链接..." name="pictureAddress" type="text">
        </div>
      </div>
      <div class="field">
        <label>描述</label>
        <textarea placeholder="请输入描述..." name="pictureDescription" type="text" style="height: 80px"></textarea>
      </div>
      <div class="actions">
        <div class="ui primary submit button">提交</div>
        <div class="ui clear button">重置</div>
      </div>
    </form>
  </div>

</div>
<div class="ui m-container-alter" th:unless="${#strings.isEmpty(messageFailed)}">
  <div class="ui negative message">
    <i class="close icon"></i>
    <div class="header">非常抱歉</div>
    <p th:text="${messageFailed}">Failed</p></div>
</div>
<div class="ui m-container-alter" th:unless="${#strings.isEmpty(messageSuccessful)}">
  <div class="ui success message">
    <i class="close icon"></i>
    <div class="header">成功</div>
    <p th:text="${messageSuccessful}">Successful</p></div>
</div>
<br>

<!--确认删除-->
<div class="ui tiny modal">
  <i class="close icon"></i>
  <div class="header">
    图片删除
  </div>
  <div class="content">
    <div class="description" name="descriptionDel">
      确定要删除该图片嘛？仔细想想看哦~ 或许它记录着你某个瞬间？
    </div>
  </div>
  <div class="actions">
    <button class="ui secondary button" id="confirmDel">
      确认
    </button>
    <button class="ui cancel button">
      取消
    </button>
  </div>
</div>

<!--确认注销-->
<div th:fragment="destroyAccount" class="ui destroy modal">
  <i class="close icon"></i>
  <div class="header">
    账号注销
  </div>
  <div class="content">
    <div class="ui form warning">
      <div class="field">
        <label>确认密码</label>
        <input type="password" name="password" placeholder="请输入密码...">
      </div>
      <div class="ui warning message">
        <div class="header">注销提醒！</div>
        <ul class="list">
          <li>只有填入你的账号密码, 你才能注销帐号</li>
          <li>注销账号, 意味着你的账号信息全部清空</li>
        </ul>
      </div>
    </div>
  </div>
  <div class="actions">
    <button class="ui secondary button" id="confirmDestroy">
      确认
    </button>
    <button class="ui cancel button">
      取消
    </button>
  </div>
</div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.js"></script>
<script src="../static/lib/picture/js/jkresponsivegallery.js"
        th:src="@{/lib/picture/js/jkresponsivegallery.js}"></script>
<script src="../static/lib/waypoints/jquery.waypoints.min.js"
        th:src="@{/lib/waypoints/jquery.waypoints.min.js}"></script>
<!--<script src="https://fastly.jsdelivr.net/gh/stevenjoezhang/live2d-widget/autoload.js"></script>-->
<script>

    $('.ui.dropdown').dropdown({
        on: 'hover'
    });

    $('.menu.toggle').click(function () {
        $('.m-item').toggleClass('m-mobile-hide');
    });

    // 初始化checkbox组件
    $('.ui.checkbox').checkbox();

    $(function () {
        $('.rthumbnail').responsivegallery();
    });

    $('#addPicture').click(() => {
        $('.ui.addPicture.modal').modal('show');
    })

    $('.clear.button').click(() => {
        $('.ui.error.message').css('display', 'none');
    });

    $('.submit.button').on('click', function () {
        $('.ui.error.message').css('display', 'block');
    })

    // 监听checkbox的状态改变
    $('.ui.checkbox input[type="checkbox"]').on('change', function () {
        const isChecked = $(this).is(':checked');

        if (isChecked) {
            // 当checkbox被选中时显示按钮
            $('#picture-main .edit-delete-buttons').show();
        } else {
            // 当checkbox未被选中时隐藏按钮
            $('#picture-main .edit-delete-buttons').hide();
        }
    });

    function deleteAccount() {
        $('.destroy.modal').modal('show');

        $('#confirmDestroy').click(async () => {
            var searchParams = new URLSearchParams();
            searchParams.append("password", $("[name='password']").val());

            const response = await fetch("/dev/login/delete", {
                method: 'POST',
                redirect: 'follow', // 允许fetch跟随重定向
                body: searchParams
            });
            const data = await response.json();
            console.log(data)
            if (data.status === "error") {
                alert(data.message);
                window.location.href = data.redirectUrl;
            } else if (data.status === "success") {
                alert(data.message);
                // 重定向到指定URL
                window.location.href = data.redirectUrl;
            }
        })
    }

    // 使用fetch或XMLHttpRequest等进行Ajax请求
    function editPicture(pictureId) {
        const url = '/dev/picture/me/' + pictureId;
        // 发起GET请求
        fetch(url, {
            method: 'GET',
            headers: {
                'Content-Type': 'application/json'
            }
        }).then(response => {
            if (!response.ok) {
                throw new Error('Network response was not ok');
            }
            return response.json(); // 将返回的对象转为JS的JSON对象
        }).then(data => {
            $('.ui.editPicture.modal').modal('show');

            // 填充form表单(不用转json格式)
            const form = $('.ui.editPicture.modal form');
            form.find('input[name="id"]').val(data.id);
            form.find('input[name="userId"]').val(data.userId);
            form.find('input[name="pictureName"]').val(data.pictureName);
            form.find('input[name="pictureAddress"]').val(data.pictureAddress);
            form.find('textarea[name="pictureDescription"]').val(data.pictureDescription);
        }).catch(error => console.error('Error:', error));
    }

    function deletePicture(pictureId) {
        $('.tiny.modal').modal('show');

        $('#confirmDel').click(() => {
            const url = '/dev/picture/me/delete/' + pictureId;
            // 发起GET请求
            fetch(url, {
                method: 'GET',
                redirect: 'follow', // 允许fetch跟随重定向
                headers: {
                    'Content-Type': 'application/json'
                }
            }).then(response => {
                if (!response.ok) {
                    throw new Error('Failed to delete picture');
                }
                // 如果服务器返回了Location头部，可以手动处理重定向(...不懂...)
                const myLocation = response.headers.get('Location');
                if (myLocation) {
                    window.location.href = myLocation;
                } else {
                    location.reload();
                }
            }).catch(error => console.error('Error:', error));
        });
    }

    $('.ui.form').form({
        fields: {
            pictureName: {
                rules: [{
                    type: 'empty',
                    prompt: '图片名称不能为空'
                }]
            },
            pictureAddress: {
                rules: [{
                    type: 'empty',
                    prompt: '图片链接不能为空'
                }]
            }
        },
    });

    $('.message .close').on('click', function () {
        $(this).closest('.message').transition('fade');
    });

    // 绑定退出按钮的点击事件
    $('#logout-link').on('click', function (event) {
        // 清除 sessionStorage
        window.sessionStorage.clear();
    });

</script>

</body>
</html>